package pers.vic.generator.renren.controller;

import java.io.IOException;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import pers.vic.base.controller.BaseConsoleController;
import pers.vic.base.pager.Lookup;
import pers.vic.base.pager.PageInfo;
import pers.vic.generator.renren.model.TableEntity;
import pers.vic.generator.renren.service.GeneratorService;

/**
 * 自动生成代码
 * @author VIC
 */
@Controller
@RequestMapping("/generator")
public class GeneratorController extends BaseConsoleController{
	
	@Resource
	private GeneratorService generatorService;

	/**
	 * 数据库表列表
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/list/", method = RequestMethod.GET)
	public String list(Model model){
		PageInfo<TableEntity> data = generatorService.list(getLookup());
		model.addAttribute("pager", data);
		return "generator/list";
	}
	
	public Lookup instanceLookup() {
		return new TableEntity();
	} 
	
	/**
	 * 查询
	 */
	@RequestMapping(value = "/list/", method = RequestMethod.POST)
	public String search(TableEntity lookup){
		setLookup(lookup);
		return "redirect:/generator/list/";
	}
	
	/**
	 *详情页 
	 */
	@RequestMapping(value = "/list/{tableName}", method = RequestMethod.GET)
	public String detail(@PathVariable String tableName, 
			@RequestParam(required = false) String packageName,
			@RequestParam(required = false) String moduleName,
			Model model){
		Map<String, String> data = generatorService.findTableDetail(tableName, packageName, moduleName);
		model.addAttribute("data",data);
		return "generator/form";
	}
	
	/**
	 * 导出
	 * @throws IOException 
	 */
	@RequestMapping(value = "/export", method = RequestMethod.POST) 
	public void export(@RequestParam String[] tableNames,  
			@RequestParam(required = false) String packageName,
			@RequestParam(required = false) String moduleName,
			HttpServletResponse response) throws IOException {
		System.out.println("packageName=" + packageName +  " moduleName=" + moduleName);
		byte[] data = generatorService.generatorCode(tableNames, packageName, moduleName);
		response.reset();  
        response.setHeader("Content-Disposition", "attachment; filename=\"generator-vic.zip\"");  
        response.addHeader("Content-Length", "" + data.length);  
        response.setContentType("application/octet-stream; charset=UTF-8");  
  
        IOUtils.write(data, response.getOutputStream());  
	}

}
